package cn.com.haopy.dataes.es.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class EsDataService {



    public static void query() {
         Log logger = LogFactory.getLog(EsDataService.class);
        // 设置验证信息，填写账号及密码
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("elastic", "Haopy@2023"));
        // 初始化 RestClient, hostName 和 port 填写集群的内网 VIP 地址与端口
        RestClientBuilder builder = RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"));
        // 设置认证信息
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
        // 设置超时时间
        //builder.setMaxRetryTimeoutMillis(10000);
        // 由Low Level Client构造High Level Client
        RestHighLevelClient client = new RestHighLevelClient(builder);

        // 索引文档
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("user", "bellen");
        jsonMap.put("name", new Date());
        jsonMap.put("message", "trying out Elasticsearch");
        IndexRequest indexRequest = new IndexRequest("posts", "doc", "1")
                .source(jsonMap);
        RequestOptions options = RequestOptions.DEFAULT.toBuilder().build();
        try {
            // 获取响应结果
            IndexResponse indexResponse = client.index(indexRequest, options);
            String index = indexResponse.getIndex();
            String type = indexResponse.getType();
            String id = indexResponse.getId();
            long version = indexResponse.getVersion();

            if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
                logger.info("doc indexed, index: " + index + ", type:" + type + ",id:" + id + ",version:" + version);
            } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
                logger.info("doc updated, index: " + index + ", type:" + type + ",id:" + id + ",version:" + version);
            }
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.CONFLICT) {
                logger.error("version conflict");

            }
        } catch (Exception e) {
            logger.error("execute index api failed, " + e.toString());
        }


        // 查询文档
        GetRequest getRequest = new GetRequest(
                "posts",
                "doc",
                "1");
        try {
            // 获取响应结果
            //GetResponse getResponse = client.get(getRequest);
            GetResponse getResponse = client.get(getRequest, options);
            String index = getResponse.getIndex();
            String type = getResponse.getType();
            String id = getResponse.getId();
            if (getResponse.isExists()) {
                long version = getResponse.getVersion();
                String sourceAsString = getResponse.getSourceAsString();
                logger.info("get doc, index: " + index + ", type:" + type + ",id:" + id + ",version:" + version + ", source:" + sourceAsString);
            }
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {
                logger.warn("doc not found");
            }
        } catch (Exception e) {
            logger.error("execute get api failed, " + e.toString());
        }

        // 关闭客户端
        try {
            client.close();
        } catch (Exception e) {
            logger.error("close rest client exception:" + e.toString());
        }
    }

    public static void main(String[] args) {
        query();
    }
}